package cc.chinagps.gateway.unit.eg.upload.cmds;

import cc.chinagps.gateway.log.LogManager;
import cc.chinagps.gateway.unit.UnitServer;
import cc.chinagps.gateway.unit.UnitSocketSession;
import cc.chinagps.gateway.unit.eg.define.EGDefines;
import cc.chinagps.gateway.unit.eg.pkg.EGPackage;
import cc.chinagps.gateway.unit.eg.upload.DeviceInfoManager;
import cc.chinagps.gateway.unit.eg.upload.bean.EGDevice;
import cc.chinagps.gateway.unit.eg.util.EGUploadUtil;
import cc.chinagps.gateway.util.HexUtil;
import cc.chinagps.gateway.util.SingletonFactory;
import org.apache.log4j.Logger;

public class Cmd10 extends CheckLoginHandler {
    private Logger logger_debug = Logger.getLogger(LogManager.LOGGER_NAME_DEBUG);

    @Override
    public boolean handlerPackageSessionChecked(EGPackage pkg, UnitServer server, UnitSocketSession session)
            throws Exception {
        byte[] data = pkg.getData();
        String mcuChipId = HexUtil.byteToHexStr(data).toUpperCase();
        String deviceId = session.getUnitInfo().getCallLetter();
        EGDevice egDevice = SingletonFactory.getInstance(DeviceInfoManager.class).getEGDevice(mcuChipId);
        if (egDevice != null) {
            egDevice.setDeviceId(deviceId);
            String authCode = egDevice.getChipAuthCode();
            byte[] resData = authCode.getBytes(EGDefines.CHARSET);
            EGUploadUtil.msgAck(session, pkg, resData);
            logger_debug.debug("[EG][Cmd10][" + deviceId + "]mcuChipId is:" + mcuChipId + ",response authCode is:" + authCode);
        } else {
            logger_debug.debug("[EG][Cmd10][" + deviceId + "]authCode is not existed,curr mcuChipId is:" + mcuChipId);
        }
        return true;
    }
}